import { useField, useForm } from '@formily/react';
import { toJS } from '@formily/reactive';
import EditableTable, { IColumns } from '@inbiz/basic/EditableTable';
import { useQueryFields } from '@inbiz/hooks';
import { Field } from '@formily/core';
import { Button, message, Modal, Tooltip } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { forwardRef, useCallback, useMemo, useRef, useState } from 'react';
import { getMessage, TextWidget } from '@inbiz/react';
import FieldForm from './FieldForm';
import AuthForm, { useAuth } from '@inbiz/basic/AuthForm';
import config from './shared';
// import ShowField, { IShowFieldRef } from './ShowField';
type IProps = {
  value: any;
  onChange: (value: any) => void;
};

// 生成随机字符串

const SettingView = (props: IProps) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const form = useForm();
  const formItemsRef = useRef({ formItems: props.value?.formItems });
  const [choosedAuth, changeHandle, generateFlag] = useAuth();
  const authOption = useMemo(() => {
    return (choosedAuth?.allInfo?.Children || []).map((ele) => ({
      value: ele.ObjectValue,
      label: ele.ObjectValue + `(${getMessage(ele.ObjectName)})`,
    }));
  }, [choosedAuth]);
  const takeMessage = useField().takeMessage;
  const showModal = async () => {
    // 此处获取对应eform示例框的对应的数据
    if (!form.fields['form.senior.soure.x-component-props.sourceModel'] as unknown as Field) {
      message.warn(getMessage('Tag.pleaseSelectModelQuery'));
      return;
    }

    setIsModalVisible(true);
  };

  const handleOk = async () => {
    const res = await tableRef.current.getData();
    const flagList = res.map((ele) => ({ value: ele.operationflag, label: ele.operationName }));
    await generateFlag(flagList);
    props.onChange({
      table: res,
      formItems: {
        ...formItemsRef.current.formItems,
      },
      auth: choosedAuth?.value,
    });
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const tableRef = useRef<{
    // 获取数据， 会触发校验
    getData: () => Promise<[]>;
    // 主动校验
    valid: () => Promise<Object>;
    // 更新内部数据
    updateSource: (id: string, data: object) => boolean;
  }>();
  return (
    <div>
      <Button type="primary" onClick={showModal}>
        <TextWidget>Tag.config</TextWidget>
      </Button>
      <Modal
        width={900}
        title={getMessage('Tag.operateConfig')}
        okText={getMessage('Tag.btn.ok')}
        cancelText={getMessage('Tag.btn.cancel')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        destroyOnClose
      >
        <FieldForm
          initialValues={props.value?.formItems}
          formItemsRef={formItemsRef}
          fields={config().formItems}
          layout={(config() as any).layout}
        />
        <AuthForm
          initialValues={props.value?.auth}
          // pageOutId={menuModal.selected.PageOutId}
          onChange={changeHandle}
        />
        <TableBox
          form={form}
          authOptions={authOption}
          ref={tableRef}
          value={props.value.table || []}
        />
      </Modal>
    </div>
  );
};

const opArr = [
  {
    value: 'add',
    label: 'Tag.btn.add',
  },
  {
    value: 'delete',
    label: 'Tag.btn.delete',
  },
  {
    value: 'read',
    label: 'Tag.btn.search',
  },
  {
    value: 'edit',
    label: 'Tag.btn.edit',
  },
];

const TableBox = forwardRef(({ form, value, authOptions }: any, ref) => {
  const sourceModel = form.query('form.senior.soure.x-component-props.sourceModel').take()! as {
    value: string;
  };
  const [fieldList] = useQueryFields({
    key: sourceModel?.value,
    //@ts-ignore
    appId: form.appInfo.appId,
  });
  const [dataSource, setDataSource] = useState(toJS(value) || []);

  const options = [];
  const columns: IColumns = useMemo(() => {
    fieldList.forEach((item) => {
      options.push({ value: item.value, label: item.label });
    });
    return [
      {
        dataIndex: 'operationType',
        title: getMessage('Tag.operateType'),
        isIdentical: true,
        width: 150,
        editData: {
          afterEdit: (value: string, record: any) => {
            const label = opArr.find((item) => item.value === value)?.label;
            record.operationName = label;
            if (value === 'delete') {
              record.link = undefined;
            }
            if (value != 'read' || value != 'edit') {
              record.field = '';
            }
            return record;
          },
          // beforEdit?: (record: any) => boolean | object;
          type: 'Select',
          options: opArr.map((ele) => ({ ...ele, label: getMessage(ele.label) })),
          showSearch: true,
          rules: [
            {
              required: true,
            },
          ],
        },
        // render: (value: string) => {
        //   if (value) {
        //     return opArr.find((item) => item.value === value)?.label;
        //   } else {
        //     return '';
        //   }
        // },
      },
      {
        dataIndex: 'operationflag',
        title: (
          <span>
            <span style={{ paddingRight: '10px' }}>
              <TextWidget>Tag.symbol</TextWidget>
            </span>
            <Tooltip title={getMessage('Tag.symbolInterpretation')}>
              <ExclamationCircleOutlined />
            </Tooltip>
          </span>
        ),
        isIdentical: true,
        width: 150,
        editData: {
          // beforEdit?: (record: any) => boolean | object;
          type: 'AutoComplete',
          // rules: [
          //   {
          //     required: true,
          //   },
          // ],
          options: authOptions,
        },
      },
      {
        dataIndex: 'operationName',
        title: getMessage('Tag.operateName'),
        isIdentical: true,
        width: 150,
        editData: {
          type: 'MultilingualInput',
        },
        render: (value) => {
          return getMessage(value);
        },
      },
      {
        dataIndex: 'link',
        title: getMessage('Tag.pageName'),
        width: 150,
        editData: {
          type: 'PageSelect',
          beforEdit: (record: { operationType?: string }) => {
            if (record?.operationType === 'delete') {
              return false;
            } else {
              return true;
            }
          },
        },
      },
      {
        dataIndex: 'field',
        title: getMessage('Tag.filed'),
        width: 150,
        editData: {
          beforEdit: (record: any) => record.operationType == 'read' || record.operationType == 'edit',
          type: 'Select',
          options,
          showSearch: true,
          filterOption: (input, option) => {
            return (option?.children ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
          },
        }
      },
    ];
  }, [fieldList, authOptions]);

  // useEffect(() => {
  //   if (options?.length > 0) {
  //     const nowDataSource = dataSource.map((item: any) => {
  //       if (options.length > 0 && options?.filter((option: any) => option.value === item.field)?.length) {
  //         return item;
  //       } else {
  //         item.field = undefined
  //         return item;
  //       }
  //     })
  //     setDataSource(nowDataSource)
  //   }
  // }, [fieldList])
  const handleAdd = useCallback(() => {
    return { id: Date.now() };
  }, []);
  return (
    <EditableTable
      rowKey={'id'}
      columns={columns}
      dataSource={dataSource}
      onAdd={handleAdd}
      ref={ref}
    />
  );
});

export default SettingView;
